iT邦幫忙

2025 iThome 鐵人賽

DAY 20
0
Software Development

30天收斂後端開發心法系列 第 20

30天收斂後端開發心法 - (20) Git Hook

  • 分享至 

  • xImage
  •  

在開發規範會議中,我們曾討論「如何具體落實團隊的開發流程規範」,其中一個具體做法就是使用 Git Hook:

在 commit 前,自動執行檢查流程,以確保程式品質與團隊一致性。

常見的 Git Hook 自動檢查項目:

  • 檢查 commit message 是否符合規範(如 Conventional Commits)
  • 使用 vendor/bin/pint 自動格式化程式碼(依照 PSR-12)
  • 自動執行測試,確保變更不會破壞原有功能

那什麼是 Git Hook?

Git Hook 是一組可以掛載在 Git 生命週期上的腳本,用來執行自定任務。

例如:在你 commit、push、merge、checkout 等動作時,自動執行檢查邏輯。

原理說明:

Git 預設提供一組 hook 檔案範例放在 .git/hooks/
當你建立指定名稱的腳本檔(如 pre-commit、commit-msg)並加上可執行權限時,Git 就會在對應事件發生時自動執行該腳本

實作範例:檢查 Commit Message 格式

假設我們要落實 Conventional Commits 規範,以下是一個 commit-msg hook 的範例。

步驟一:建立腳本目錄並撰寫 hook

mkdir -p scripts
touch scripts/commit-msg
chmod +x scripts/commit-msg

編輯 scripts/commit-msg 內容:

#!/bin/sh

檢查 commit message 是否符合 Conventional Commit 格式

COMMIT_MSG_FILE=$1
COMMIT_MSG=$(head -n 1 "$COMMIT_MSG_FILE")

定義格式規則:type(scope): subject

HEADER_PATTERN="^(feat|fix|docs|style|refactor|test|chore)(\\(.+\\))?: .{1,100}$"
if ! echo "$COMMIT_MSG" | grep -qE "$HEADER_PATTERN"; then
    echo "Commit message 不符合 Conventional Commit 格式"
    echo "格式應為:type(scope): subject"
    echo "其中 type 可為 feat, fix, docs, style, refactor, test, chore"
    echo "範例:feat(auth): add user authentication"
    exit 1
fi

步驟二:安裝 Git Hook

你可以手動安裝,或使用工具自動安裝(建議使用工具,團隊共享時更方便)。

手動方式:

將 scripts/commit-msg 複製到 .git/hooks/ 目錄:

cp scripts/commit-msg .git/hooks/commit-msg
chmod +x .git/hooks/commit-msg

試試提交一個不合規範的 message:

git commit -m "update user logic"

輸出錯誤訊息:

Commit message 不符合 Conventional Commit 格式
格式應為:type(scope): subject

有興趣的話可以參考 Git 官方 Hook 文件:
🔗 https://git-scm.com/docs/githooks


上一篇
30天收斂後端開發心法 - (19) HTTP Client
下一篇
30天收斂後端開發心法 - (21) HTTP Request
系列文
30天收斂後端開發心法30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言